﻿using System;
using System.Collections.Generic;
using mmCore.Interfaces;

namespace mmSubProvider
{
    public class SubProvider : ISubProvider
    {
        #region MEMBERS

        private int _mSeason;
        private int _mEp;
        private string _mTitle;

        #endregion MEMBERS

        #region EVENTS

        public event Action<string> OnFound;

        #endregion EVENTS

        #region METHODS

        public bool FindSubtitle(string title, int season, int episode)
        {
            if(string.IsNullOrEmpty(title) || season <= 0 || episode <= 0)
            {
                return false;
            }

            _mSeason = season;
            _mEp = episode;
            _mTitle = title;

            var ss = new SubSearch();
            ss.OnFound += ss_OnFound;
            ss.Search(title);

            return true;
        }

        #endregion METHODS

        #region PRIVATE

        void ss_OnFound(List<SubSearchResult> result)
        {
            SubSearchResult rst = null;
            if (result.Count != 1)
            {
                foreach(var ssr in result)
                {
                    if(ssr.Title.ToLower() == _mTitle.ToLower())
                    {
                        rst = ssr;
                        break;
                    }
                }
                if(rst == null)
                {
                    if (OnFound != null)
                    {
                        OnFound(string.Empty);
                    }
                    return;
                }
            }
            else
            {
                rst = result[0];
            }

            var sd = new SubDownload();
            sd.OnSubtitleAvailable += sd_OnSubtitleAvailable;
            sd.SubtitleAvailable(rst, _mSeason, _mEp);
        }

        void sd_OnSubtitleAvailable(SubSearchResult result, string url)
        {
            if(OnFound != null)
            {
                OnFound(url);
            }
        }

        #endregion PRIVATE
    }
}
